<template>
  <div class="upload-container">
    <el-button
      icon="el-icon-document"
      size="mini"
      :style="{background:color,borderColor:color}"
      type="primary"
      @click=" dialogVisible=true"
    >转换
    </el-button>
    <el-dialog
      title="转换"
      :visible.sync="dialogVisible"
      width="80%"
      append-to-body
      :close-on-click-modal="false"
      @opened="handleOpend"
    >
      <el-row>
        <el-form ref="form" :inline="true" label-width="80px">
          <el-form-item label="类型">
            <el-select v-model="transtype" placeholder="类型" size="small" filterable clearable>
              <el-option label="divi折叠FAQ" value="divi-faq" />
              <el-option label="shortcode" value="shortcode" />
              <el-option label="搜索链接" value="search_link" />
              <el-option label="rank math how to" value="rank-math-howto" />
              <el-option label="rank math FAQ" value="rank-math-faq" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="transtype === 'divi-faq'" label="AI模板">
            <el-input v-model="ai_template"style="width: 300px" />
          </el-form-item>
          <el-form-item v-if="transtype === 'divi-faq'" label="引擎">
            <el-select v-model="engine" style="width: 100px" placeholder="选择引擎" size="small" filterable clearable>
              <el-option label="chatgpt" value="gpt-3.5-turbo" />
              <el-option label="一般" value="text-davinci-003" />
              <el-option label="普通" value="text-davinci-002" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否显示">
            <el-switch
              v-model="visible"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
        </el-form>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form ref="form" :label-position="&quot;top&quot;" label-width="80px">
            <el-form-item label="内容">
              <el-input v-model="main_point" type="textarea" :rows="10" placeholder="输入" />
            </el-form-item>
            <el-form-item>
              <el-button :loading="loading" type="primary" @click="HandleGetContent">立即创建</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <span>反馈结果:</span>
          <el-collapse v-if="transtype === 'shortcode'" v-model="activeName" accordion>
            <el-collapse-item v-for="i in shotcodes" :key="i.code" :title="i.code">
              <el-input v-model="i.code" />
              <el-input v-model="i.value" type="textarea" :rows="12" />
              <el-button type="primary" @click="handleUsetContent(i.value)">使用</el-button>
            </el-collapse-item>
          </el-collapse>
          <el-input v-model="content" type="textarea" :rows="12" />
          <el-popover
            placement="top"
            width="400"
            trigger="click"
          >
            <div v-html="content" />
            <el-button slot="reference" type="success" size="mini" style="width: 100%">查看</el-button>
          </el-popover>
        </el-col>
      </el-row>
      <span v-if="content.length" slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="handInsert">插入</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
require('vue-select-image/dist/vue-select-image.css')
import {
  WriteHtmlPiece
} from '@/api/cms/openai'
import qs from 'qs'

import { Get as GetShortCode, SearchLink } from '@/api/cms/shortcode'

export default {
  name: 'Transblock',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      template_type: '写段落',
      main_point: '',
      topic: '',
      dialogVisible: false,
      transtype: 'divi-faq',
      shortcode: '',
      visible: false,
      content: '',
      activeName: '',
      shotcodes: [],
      engine: 'text-curie-001',
      ai_template: 'write a blog section about "{keyword}"',
      loading: false
    }
  },
  computed: {},
  methods: {
    handleOpend() {
      const content = window.tinymce.get(this.id).selection.getContent()
      if (content) {
        this.topic = content
        this.main_point = content
      }
    },
    handleInsertTemplate(value) {
      console.log(value)
    },
    create_rank_math_howto() {
      if (!this.main_point) {
        this.$message.warning('清选择内容')
        this.loading = false
        return
      }
      const rank_config = {
        description: '',
        steps: [],
        hasDuration: false
      }
      const el = document.createElement('html')
      el.innerHTML = '<html>' + this.main_point + '</html>'
      const p = el.getElementsByTagName('p')[0]
      if (p && p.textContent.length) {
        rank_config.description = p.textContent
      }
      const lis = el.getElementsByTagName('li')
      for (let i = 0; i < lis.length; i++) {
        const content = lis[i].textContent
        const step = i + 1
        rank_config.steps.push({ 'title': 'STEP ' + step, content: content, visible: this.visible })
      }
      this.content = '<!-- wp:rank-math/howto-block ' + JSON.stringify(rank_config) + ' -->'
      this.content += '<div class="wp-block-rank-math-howto-block">'
      for (let i = 0; i < rank_config.steps.length; i++) {
        this.content += '<div class="rank-math-howto-step">'
        this.content += '<h3 class="rank-math-howto-title">' + rank_config.steps[i].title + '</h3>'
        this.content += '<div class="rank-math-howto-content">' + rank_config.steps[i].content + '</div></div>'
      }
      this.content += '</div><!-- /wp:rank-math/howto-block -->'
      console.log(this.content)
      this.loading = false
    },
    create_rank_math_faq() {
      if (!this.main_point) {
        this.$message.warning('清选择内容')
        this.loading = false
        return
      }
      const rank_config = {
        questions: []
      }
      const el = document.createElement('html')
      el.innerHTML = '<html>' + this.main_point + '</html>'
      const h2 = el.getElementsByTagName('h2')[0]
      const item = {
        'title': h2.textContent,
        'content': '',
        visible: this.visible
      }
      const lis = el.getElementsByTagName('p')
      for (let i = 0; i < lis.length; i++) {
        item.content += lis[i].textContent
        if (i + 1 !== lis.length) {
          item.content += '\u003cbr\u003e'
        }
      }
      rank_config.questions.push(item)
      this.content = '<!-- wp:rank-math/faq-block ' + JSON.stringify(rank_config) + ' -->'
      for (let i = 0; i < rank_config.questions.length; i++) {
        this.content += '<div class="rank-math-faq-item">'
        this.content += '<h3 class="rank-math-question">' + rank_config.steps[i].title + '</h3>'
        this.content += '<div class="rank-math-answer">' + rank_config.steps[i].content + '</div></div>'
      }
      this.content += '\n<!-- /wp:rank-math/howto-block -->'
      console.log(this.content)
    },
    create_divi_faq() {
      if (!this.main_point) {
        this.$message.warning('清输入内容，每行一个问题')
        this.loading = false
        return
      }
      const questions = this.main_point.split('\n')
      WriteHtmlPiece({ task: 'divi-faq', prompts: questions, ai_template: this.ai_template }).then(response => {
        this.content = response.html
        this.loading = false
      }).catch(e => {
        this.loading = false
      })
    },
    create_shortcode() {
      if (!this.main_point) {
        this.$message.warning('清输入内容，每行一个问题')
        this.loading = false
        return
      }
      GetShortCode(null, qs.stringify({
        kw: this.main_point,
        pagesize: 100,
        page: 1
      })).then(response => {
        this.shotcodes = response.data.data
        this.content = response.data.data[0].value
        this.shortcode = '[' + response.data.data[0].code + ']'
        this.loading = false
      }).catch(e => {
        this.loading = false
      })
    },
    search_link() {
      if (!this.main_point) {
        this.$message.warning('清输入内容，每行一个问题')
        this.loading = false
        return
      }
      SearchLink(null, qs.stringify({
        kw: this.main_point,
        pagesize: 100,
        page: 1
      })).then(response => {
        this.content = response.data.data.join('\n')
        this.loading = false
      }).catch(e => {
        this.loading = false
      })
    },
    HandleGetContent() {
      this.loading = true
      this.content = ''
      if (this.transtype === 'rank-math-howto') {
        this.create_rank_math_howto()
      } else if (this.transtype === 'rank-math-faq') {
        this.create_rank_math_faq()
      } else if (this.transtype === 'divi-faq') {
        this.create_divi_faq()
      } else if (this.transtype === 'shortcode') {
        this.create_shortcode()
      } else if (this.transtype === 'search_link') {
        this.search_link()
      }
      navigator.clipboard.writeText(this.content).then(function() {
        this.$message.success('内容已经复制到剪切板')
      }, function() {
        this.$message.error('复制失败')
      })
      this.loading = false
    },
    handleUsetContent(content) {
      this.content = content
      this.$message.success('替换成功')
    },
    handInsert() {
      this.$emit('successCBK', { content: this.content })
      this.dialogVisible = false
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .editor-slide-upload {
    margin-bottom: 20px;
    :deep(.el-upload--picture-card) {
      width: 100%;
    }
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }
  .el-dialog__body {
    margin-top: 5px;
  }
</style>

